package com.hackaton.touringengine;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.google.appengine.repackaged.org.json.JSONArray;
import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;
import com.hackaton.touringengine.entity.User;
import com.hackaton.touringengine.persistence.PersistenceFactory;

@SuppressWarnings("serial")
public class UserListServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		PersistenceManager pm = PersistenceFactory.get().getPersistenceManager();
		try {
		    Query query = pm.newQuery(User.class);
		    query.setOrdering("name asc");
		    writeResult(resp, (List<User>)query.execute(), 0);
		} catch (Exception e) {
			writeResult(resp, null, 1);
		} finally {
			pm.close();
		}
	}
	
	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}



	private void writeResult(HttpServletResponse resp, List<User> users, int resultCode) throws IOException {
		resp.setContentType("text/plain");
		JSONObject resultJSON = new JSONObject();
		JSONObject statusJSON = new JSONObject();
		try {
			if (resultCode == 0) {
				JSONArray userArray = new JSONArray();
				int i = 0;
				for (User user : users) {
					JSONObject userJSON = new JSONObject();
					userJSON.put("id", user.getKey().getName());
					userJSON.put("name", user.getName());
					userArray.put(i++, userJSON);
				}
				resultJSON.put("users", userArray);
			}
			statusJSON.put("code", resultCode);
			resultJSON.put("status", statusJSON);
			resp.setStatus(200);
			resp.getWriter().println(resultJSON.toString());
		} catch (JSONException e1) {
			//this won't happen
		}
	}
}
